package com.ebei.platform.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: 微服务token验证工具类
 * 
 * @date:2017年10月11日
 * @Copyright (c) 2017 一碑科技
 * @version
 * @author zhugl
 */
public class TokenValidUtil {

	private static String TOKEN_VALID_SWITCH;

	private static String SWAGGER_SWITCH;

	private static String BYG_HOST;

	private static String BYG_ATTACHMENT_HOST;
	private static Base64 base64 = null;

    public static void setTokenValidSwitch(String tokenValidSwitch) {
        TOKEN_VALID_SWITCH = tokenValidSwitch;
    }

    public static void setSwaggerSwitch(String swaggerSwitch) {
        SWAGGER_SWITCH = swaggerSwitch;
    }

    public static void setBygHost(String bygHost) {
        BYG_HOST = bygHost;
    }

    public static void setBygAttachmentHost(String bygAttachmentHost) {
        BYG_ATTACHMENT_HOST = bygAttachmentHost;
    }

	/*static{
		TOKEN_VALID_SWITCH = new TokenUtils().getTOKEN_VALID_SWITCH();
		if (TOKEN_VALID_SWITCH == null) {
			TOKEN_VALID_SWITCH = "";
		}
		BYG_HOST = new TokenUtils().getBYG_HOST();
		if (BYG_HOST == null) {
			BYG_HOST = "";
		}
		SWAGGER_SWITCH = new TokenUtils().getSWAGGER_SWITCH();
		if (SWAGGER_SWITCH == null) {
			SWAGGER_SWITCH = "";
		}
		BYG_ATTACHMENT_HOST = new TokenUtils().getBYG_ATTACHMENT_HOST();
		if (BYG_ATTACHMENT_HOST == null) {
		    BYG_ATTACHMENT_HOST = "";
		}
	}*/

	private static Logger logger = LoggerFactory.getLogger(TokenValidUtil.class);

    /**
     * token是否验证通过
     * @param httpreques
     * @return
     */
    public static JSONObject isTokenPass(HttpServletRequest httprequest) {
        JSONObject result = new JSONObject();
        result.put("ErrorCode", 1);
        result.put("ErrorMessage", "this token is invalid.");
        result.put("Data", "");
        if ("false".equals(TOKEN_VALID_SWITCH)) {
            result.put("ErrorCode", 0);
            result.put("ErrorMessage", "");
            return result;
        }
        
        String authorization = getAuthorization(httprequest);
        if (StringUtils.isEmpty(authorization)) {
            result.put("ErrorCode", 1);
            result.put("ErrorMessage", "token串为空");
            return result;
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put(RestfulConstants.TOKEN_VALID_KEY, authorization);
        String url = TokenValidUtil.getResquestUrl(RestfulConstants.HTTP_URL_VALIDATE_TOKEN);
        String msg = HttpRequestUtils.sendPost(url, params);
        if (StringUtils.isEmpty(msg)) {
            result.put("ErrorCode", 1);
            result.put("ErrorMessage", "token验证不合法");
            return result;
        }
        
        result = JSONObject.parseObject(msg);
        return result;
    }
    
    public static Map<String, String> getHeadersInfo(HttpServletRequest httpreques) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<?> headerNames = httpreques.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = httpreques.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
    
    public static String getResquestUrl(String url) {
        return BYG_HOST + url;
    }
    public static String getAttachmentResquestUrl(String url, Integer attachmentId) {
        return BYG_ATTACHMENT_HOST + url + attachmentId;
    }
    
    public static String getAttachmentResquestUrlNotAttach(String url) {
        return BYG_ATTACHMENT_HOST + url;
    }
    
    public static String getAuthorization(HttpServletRequest httpreques) {
        String authorization = null;
        Map<String, String> headerMap = getHeadersInfo(httpreques);
        authorization = headerMap.get("authorization");
        if (StringUtils.isEmpty(authorization)) {
            authorization = headerMap.get("Authorization");//app端
        }
        
        return authorization;
    }
    
    /**
     * token是否验证通过
     * @param httpreques
     * @return
     */
    public static void getInitPassUrlList(List<String> passUrlList) {
        if ("true".equals(SWAGGER_SWITCH)) {
        	passUrlList.add("/swagger");//swagger 在线文档请求
        	passUrlList.add("/api-docs");//swagger 在线文档请求
        }
    	passUrlList.add("/index.html");//判断项目启动成功后的页面
    	passUrlList.add("/druid/");//sql监控url
    	passUrlList.add("/fileExport/");//文件导出的URL
    	passUrlList.add("*.js");//静态js，css等等放行
        passUrlList.add("*.css");//静态js，css等等放行 
        //passUrlList.add("/testInfo/123");//多数据源测试接口
        //passUrlList.add("/resetPassword/resetPass");//重置密码接口
    }
    
    /**
     * 解析token
     * @param httpreques
     * @return
     */
    public static JSONObject getCurrentUserInfo(HttpServletRequest httpreques) {
        String authorization = getAuthorization(httpreques);
        logger.info("----------------------"+authorization);
        Base64 base64 = getBase64();
        String[] tokenArr = authorization.split("\\.");
        try {
            byte[] textByte = tokenArr[1].getBytes("UTF-8");
            String decodeStr = new String(base64.decode(textByte), "UTF-8");
            //logger.info("----------------------"+decodeStr);
            JSONObject userInfo = JSONObject.parseObject(decodeStr);
            return userInfo;
        } catch (UnsupportedEncodingException e) {
            logger.error(ExceptionUtils.getExceptionDetail(e));
        }
        
        return null;
    }
    
    public static Base64 getBase64() {
        if (base64 == null) {
            base64 = new Base64();
        }
        return base64;
    }
    
    public static Map<String, String> getAppLogs(HttpServletRequest httpreques) throws Exception {
        Map<String, String> resultMap = null;
        JSONObject applog = null;
        String s_applog = null;
        Map<String, String> headerMap = getHeadersInfo(httpreques);
        s_applog = headerMap.get("applog");
        if (!StringUtils.isEmpty(s_applog)) {
            try {
                applog = JSONObject.parseObject(s_applog);
            } catch (Exception e) {
                throw new Exception("获取APP日志信息时，解析请求头出错");
            }
        }
        if (applog != null) {
            resultMap = new HashMap<String, String>(8);
            resultMap.put("Address", applog.getString("Address"));
            resultMap.put("MapType", applog.getString("MapType"));
            resultMap.put("Longitude", applog.getString("Longitude"));
            resultMap.put("Latitude", applog.getString("Latitude"));
            resultMap.put("DeviceInfo", applog.getString("DeviceInfo"));
            resultMap.put("MobileModel", applog.getString("MobileModel"));
            resultMap.put("AppVersion", applog.getString("AppVersion"));
            resultMap.put("Platform", applog.getString("Platform"));
        }
        
        return resultMap;
    }
}
